package security.encrypts

import java.nio.charset.Charset
import java.security.SecureRandom
import java.util.Base64

import de.mkammerer.argon2.{Argon2Advanced, Argon2Factory}

object Argon2Encode {
  lazy val UTF8 = Charset.forName("UTF-8")
  private final lazy val ARGON2: Argon2Advanced = Argon2Factory.createAdvanced(Argon2Factory.Argon2Types.ARGON2i)

  private val ITERATIONS = 4
  private val MEMORY = 65536
  private val PARALLELISM = 2

  def hash(password: CharSequence, salt: CharSequence=randomSalt, charset: Charset = UTF8): String = {
    ARGON2.hash(ITERATIONS, MEMORY, PARALLELISM, password.toString.toCharArray, charset, salt.toString.getBytes(charset))
  }
  def verify(hash:String,password:String,charset: Charset = UTF8) = ARGON2.verify(hash,password.toCharArray,charset)

  def randomSalt={
    val salt = new Array[Byte](16)
    val r = new SecureRandom
    r.nextBytes(salt)
    Base64.getEncoder.encodeToString(salt)
  }
}
